﻿// Spun AJAX Framework
// Copyright (C) 2008 Blake Hegerle
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

using System.IO;
using System;
using System.Collections.Generic;

using LitJson;

namespace Spun.Communications
{
    using Models;
    using Models.Sequences;
    using Spun.Utility;

    public class ModelDeserializationException : Exception
    {
        public ModelDeserializationException(string Message) : base(Message) { }
        public ModelDeserializationException(string Message, Exception e)
            : base(Message, e)
        { }
    }

    public class SpunJson
    {
        public static void EnableJsonForSpun()
        {
            JsonMapper.RegisterExporter(delegate(ModelBase Model, JsonWriter Writer)
            {
                Writer.WriteObjectStart();

                foreach (var Member in Model.AllMembersValues)
                {
                    Writer.WritePropertyName(Member.Key);
                    JsonMapper.ToJson(Member.Value, Writer);
                }

                Writer.WriteObjectEnd();
            });

            JsonMapper.RegisterExporter(delegate(Sequence Seq, JsonWriter Writer)
            {
                Writer.WriteArrayStart();

                foreach (var Obj in Seq.Enumerable)
                    JsonMapper.ToJson(Obj, Writer);

                Writer.WriteArrayEnd();
            });
        }
    }

    public static class ModelContextJson
    {
        public static T ToModel<T>(this ModelContext Context, JsonReader reader)
            where T : class
        {
            return ModelJsonMapper<T>.ToModel(Context, JsonMapper.ToObject(reader));
        }

        public static T ToModel<T>(this ModelContext Context, TextReader reader)
            where T : class
        {
            return ModelJsonMapper<T>.ToModel(Context, JsonMapper.ToObject(reader));
        }

        public static T ToModel<T>(this ModelContext Context, string json)
            where T : class
        {
            return ModelJsonMapper<T>.ToModel(Context, JsonMapper.ToObject(json));
        }

        private class ModelJsonMapper<T>
            where T : class
        {
            public static T ToModel(ModelContext Context, JsonData jsonData)
            {
                if (jsonData == null)
                    return null;

                if (jsonData.IsObject == false)
                    throw new ModelDeserializationException("Cannot deserialize a model from a JSON scalar or array");

                var Instance = Context.NewProxy<T>();

                foreach (KeyValuePair<string, JsonData> Member in jsonData)
                {
                    if (Member.Value == null)
                        continue;

                    var Type = Instance.GetMemberType(Member.Key);

                    if (Member.Value.IsBoolean)
                    {
                        Instance.Update(Member.Key, (bool)Member.Value);
                    }
                    else if (Member.Value.IsDouble)
                    {
                        Instance.Update(Member.Key, (double)Member.Value);
                    }
                    else if (Member.Value.IsInt)
                    {
                        Instance.Update(Member.Key, (int)Member.Value);
                    }
                    else if (Member.Value.IsLong)
                    {
                        Instance.Update(Member.Key, (long)Member.Value);
                    }
                    else if (Member.Value.IsString)
                    {
                        Instance.Update(Member.Key, (string)Member.Value);
                    }
                    else
                    {
                        Type MapperType;
                        Type[] Arguments;

                        if (Member.Value.IsArray)
                        {
                            MapperType = typeof(ArrayJsonMapper<>);
                            Arguments = Type.GetGenericArguments();
                        }
                        else if (Member.Value.IsObject)
                        {
                            MapperType = typeof(ModelJsonMapper<>);
                            Arguments = new[] { Type };
                        }
                        else
                            throw new ModelDeserializationException("JSON Member not primitive, array or object");

                        GenericReflector.InvokeStaticVoid(
                            MapperType,
                            Arguments,
                            "Map",
                            Context, Member, Instance);
                    }
                }

                return Instance.ProxyInterface;
            }

            public static void Map(
                ModelContext Context,
                KeyValuePair<string, JsonData> Data,
                ModelBase Model)
            {
                try
                {
                    Model.Update(Data.Key, ModelJsonMapper<T>.ToModel(Context, Data.Value));
                }
                catch (Exception e)
                {
                    throw new ModelDeserializationException(
                         "Cannot deserialize a member object", e);
                }
            }
        }

        private class ArrayJsonMapper<T>
            where T : class
        {
            public static void Map(
                ModelContext Context,
                KeyValuePair<string, JsonData> Data,
                ModelBase Model)
            {
                var Seq = new FixedSequence<T>((uint)Data.Value.Count);

                for (int i = 0; i < Data.Value.Count; i++)
                    Seq[(uint)i] = ModelJsonMapper<T>.ToModel(Context, Data.Value[i]);

                try
                {
                    Model.Update<Sequence<T>>(Data.Key, Seq);
                }
                catch (Exception e)
                {
                    throw new ModelDeserializationException(
                         "Cannot deserialize an array", e);
                }
            }
        }
    }
}
